import https from 'https';
import axios, { Method } from 'axios';
import qs from 'qs';

const httpsAgent = new https.Agent({
  rejectUnauthorized: false
});
// 创建忽略 SSL 的 axios 实例
const instance = axios.create({
  httpsAgent,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    'req-agent': 'internal-access',
    'Access-Control-Allow-Origin': '*'
  }
});

// 请求默认参数
const defaultConfig = {
  url: '',
  method: 'GET' as Method,
  params: {},
  data: {},
  config: {}
};

const fetch = {
  get<T>({ config = {}, data = {}, params = {}, ...requestConfig }): Promise<T> {
    const mergeConfig = Object.assign(
      {},
      {
        ...defaultConfig,
        ...requestConfig,
        data,
        params,
        method: 'GET' as Method,
        paramsSerializer: (requestParams: any) => {
          return qs.stringify(requestParams);
        }
      },
      config
    );

    return instance.request(mergeConfig).then((res) => {
      return res.data;
    });
  }
};

export { instance, fetch as default };
